package com.february.todo.MyCalendar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.february.calendarview.Calendar;
import com.february.calendarview.CalendarLayout;
import com.february.calendarview.CalendarView;
import com.february.todo.tools.Bean_todo;
import com.february.todo.DataBase.DataBaseOperate;
import com.february.todo.tools.Bean_date;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CalendarWidget implements
        CalendarView.OnCalendarSelectListener,
        CalendarView.OnCalendarLongClickListener,
        CalendarView.OnMonthChangeListener,
        CalendarView.OnYearChangeListener,
        CalendarView.OnWeekChangeListener,
        CalendarView.OnViewChangeListener,
        CalendarView.OnCalendarInterceptListener,
        CalendarView.OnYearViewChangeListener{

    public TextView mTextMonthDay;
    public TextView mTextYear;
    public TextView mTextLunar;
    public TextView mTextCurrentDay;
    public ImageView mImgToday;
    public CalendarView mCalendarView;
    public CalendarLayout mCalendarLayout;
    public RecyclerView recyclerView;
    public SimpleTodoListAdapter mAdapter;
    public ArrayList<Bean_todo> todos;
    public Map<String, Calendar> mapTodo;

    private int mYear;
    private final Context context;

    public CalendarWidget(Context context){
        this.context=context;
    }

    @SuppressLint("SetTextI18n")
    public void initView(){

        //@SuppressLint("InflateParams") View parent= LayoutInflater.from(context).inflate(R.layout.activity_main,null);

        mTextMonthDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mCalendarLayout.isExpand()) {
                    mCalendarLayout.expand();
                    return;
                }
                mCalendarView.showYearSelectLayout(mYear);
                mTextLunar.setVisibility(View.GONE);
                mTextYear.setVisibility(View.GONE);
                mTextMonthDay.setText(String.valueOf(mYear));
            }
        });

        mImgToday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCalendarView.scrollToCurrent(true);
            }
        });

        mCalendarView.setOnYearChangeListener(this);
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnMonthChangeListener(this);
        mCalendarView.setOnCalendarLongClickListener(this, true);
        mCalendarView.setOnWeekChangeListener(this);
        mCalendarView.setOnYearViewChangeListener(this);

        //设置日期拦截事件，仅适用单选模式，当前无效
        mCalendarView.setOnCalendarInterceptListener(this);

        mCalendarView.setOnViewChangeListener(this);
        mTextYear.setText(String.valueOf(mCalendarView.getCurYear()));
        mYear = mCalendarView.getCurYear();
        mTextMonthDay.setText(mCalendarView.getCurMonth() + "月" + mCalendarView.getCurDay() + "日");
        mTextLunar.setText("今日");
        mTextCurrentDay.setText(String.valueOf(mCalendarView.getCurDay()));

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter = new SimpleTodoListAdapter(context);
        recyclerView.setAdapter(mAdapter);
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme("■");
        return calendar;
    }

    public void UpdateTodoList(String date){
        String[] t=date.split("-");
        try{
            int y=Integer.parseInt(t[0]);
            int m=Integer.parseInt(t[1]);
            int d=Integer.parseInt(t[2]);
            this.UpdateTodoList(y,m,d);
        }catch (Exception e){
            Log.i("message","UpdateTodoList");
        }
    }

    public void UpdateTodoList(int y,int m,int d){
        String date=String.valueOf(y)+"-"+String.valueOf(m)+"-"+String.valueOf(d);
        DataBaseOperate DBoprate=new DataBaseOperate(context);
        todos=DBoprate.getAllTodo();
        ArrayList<Bean_todo> todoArrayList = new ArrayList<>();
        for(int i=0;i<todos.size();i++){
            if(todos.get(i).getDate().equals(date)){
                todoArrayList.add(todos.get(i));
            }
        }
        mAdapter.clear();
        mAdapter.addAll(todoArrayList);
    }

    public void UpdateCalendar(){
        DataBaseOperate DBoprate=new DataBaseOperate(context);
        ArrayList<Bean_date> dates=new ArrayList<Bean_date>();
        dates=DBoprate.getAllDate();
        mapTodo = new HashMap<>();
        String[] date={};

        for(int i=0;i<dates.size();i++){
            date=dates.get(i).getDate().split("-");
            try {
                int y=Integer.parseInt(date[0]);
                int m=Integer.parseInt(date[1]);
                int d=Integer.parseInt(date[2]);
                int color=0xFFFE6363;
                mapTodo.put(getSchemeCalendar(y, m, d, color).toString(), getSchemeCalendar(y, m, d, color));
            }catch (Exception e){
                Log.i("message","bad date");
            }
        }
        mCalendarView.setSchemeDate(mapTodo);
    }

    public void initData() {
        this.UpdateCalendar();

        int y = mCalendarView.getCurYear();
        int m = mCalendarView.getCurMonth();
        int d = mCalendarView.getCurDay();
        this.UpdateTodoList(y,m,d);
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {
        Toast.makeText(context, String.format("%s : OutOfRange", calendar), Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        mTextLunar.setVisibility(View.VISIBLE);
        mTextYear.setVisibility(View.VISIBLE);
        mTextMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
        mTextYear.setText(String.valueOf(calendar.getYear()));
        mTextLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();

        int y = calendar.getYear();
        int m = calendar.getMonth();
        int d = calendar.getDay();
        this.UpdateTodoList(y,m,d);
    }

    @Override
    public void onCalendarLongClickOutOfRange(Calendar calendar) {
        Toast.makeText(context, String.format("%s : LongClickOutOfRange", calendar), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCalendarLongClick(Calendar calendar) {
        Toast.makeText(context, "长按不选择日期\n" + getCalendarText(calendar), Toast.LENGTH_SHORT).show();
    }

    private static String getCalendarText(Calendar calendar) {
        return String.format("新历%s \n 农历%s \n 公历节日：%s \n 农历节日：%s \n 节气：%s \n 是否闰月：%s",
                calendar.getMonth() + "月" + calendar.getDay() + "日",
                calendar.getLunarCalendar().getMonth() + "月" + calendar.getLunarCalendar().getDay() + "日",
                TextUtils.isEmpty(calendar.getGregorianFestival()) ? "无" : calendar.getGregorianFestival(),
                TextUtils.isEmpty(calendar.getTraditionFestival()) ? "无" : calendar.getTraditionFestival(),
                TextUtils.isEmpty(calendar.getSolarTerm()) ? "无" : calendar.getSolarTerm(),
                calendar.getLeapMonth() == 0 ? "否" : String.format("闰%s月", calendar.getLeapMonth()));
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onMonthChange(int year, int month) {
        Log.e("onMonthChange", "  -- " + year + "  --  " + month);
        Calendar calendar = mCalendarView.getSelectedCalendar();
        mTextLunar.setVisibility(View.VISIBLE);
        mTextYear.setVisibility(View.VISIBLE);
        mTextMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
        mTextYear.setText(String.valueOf(calendar.getYear()));
        mTextLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();
    }

    @Override
    public void onViewChange(boolean isMonthView) {
        Log.e("onViewChange", "  ---  " + (isMonthView ? "月视图" : "周视图"));
    }

    @Override
    public void onWeekChange(List<Calendar> weekCalendars) {
        for (Calendar calendar : weekCalendars) {
            Log.e("onWeekChange", calendar.toString());
        }
    }

    @Override
    public void onYearViewChange(boolean isClose) {
        Log.e("onYearViewChange", "年视图 -- " + (isClose ? "关闭" : "打开"));
    }

    /**
     * 屏蔽某些不可点击的日期，可根据自己的业务自行修改
     *
     * @param calendar calendar
     * @return 是否屏蔽某些不可点击的日期，MonthView和WeekView有类似的API可调用
     */
    @Override
    public boolean onCalendarIntercept(Calendar calendar) {
        Log.e("onCalendarIntercept", calendar.toString());
        int day = calendar.getDay();
        return day == 1 || day == 3 || day == 6 || day == 11 || day == 12 || day == 15 || day == 20 || day == 26;
    }

    @Override
    public void onCalendarInterceptClick(Calendar calendar, boolean isClick) {
        Toast.makeText(context, calendar.toString() + "拦截不可点击", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onYearChange(int year) {
        mTextMonthDay.setText(String.valueOf(year));
        Log.e("onYearChange", " 年份变化 " + year);
    }
}
